/**
 * Created by Will Bean on 2016/8/21.
 */
import React, { PropTypes, Component } from 'react'
import fetch from 'isomorphic-fetch'
import { Link } from 'react-router'

import Table from './Table'
import NavLink from './NavLink'
import style from './addStore.css'

import { myAjax, ROOTURL } from '../publicAPI/publicAPI'

class PrototypeServiceM extends Component {

    constructor (props, context) {
        super(props, context);
        console.log("初始化");
       
        this.state = {
            delete: false,
            deleteId : -1,
            dataList : [],
            hasBeenMounted : false,
            ddServiceList : []
        } ;// 初始化状态
    }

    componentWillMount() {
        console.log("将安装");
        if(!this.state.hasBeenMounted) {
            this.setState({hasBeenMounted: true});
            var url = ROOTURL + 'serv/prototype/search.api ';
            var _this = this;
            fetch(url, {
                method: 'POST',
                mode: 'cors',
                body : JSON.stringify({"where": {"dd":[["eq", false]]},
                    "order": [["id","asc"]]})
            }).then(response => {
                if (response.ok){
                    response.json().then(function (data) {
                        console.log(data)
                        _this.setState({
                            dataList: data
                        })
                    })
                }
            }).catch(function (error) {
                console.log('Request failed', error);
            });

            fetch(ROOTURL+'serv/prototype/search.api',{
                method: 'POST',
                body: JSON.stringify({
                    "where": {"dd":[["eq", true]]},
                    "order": [["id","asc"]]
                })
            }).then(res=>{
                if(res.ok){
                    res.json().then(data=>{
                        _this.setState({
                            ddServiceList:data
                        })
                    })
                }
            })
        }
    }

    componentDidMount() {
        console.log("安装成功");
    }

    handleDelete(id){
        this.setState({
            delete: !this.state.delete,
            deleteId : id
        })
    }

    changeToMin(ms){
        return parseInt(ms/60000)
    }

    handleStoreDelete(){
        var url = ROOTURL + 'serv/prototype/instance.api?id='+this.state.deleteId;
        this.setState({
            delete: !this.state.delete
        });
        fetch(url, {
            method : 'delete',
            // mode : 'no-cors',
            body: JSON.stringify({})
        }).then(res=>{
            if(res.ok){
                res.json().then(data=>{
                    location.href = '/PrototypeServiceM'
                })
            }
        });
    }
    //render thead
    tHead() {
        var data = [
            {name: "id"},
            {name: "图标"},
            {name: "标识"},
            {name: "显示名"},
            {name: "基础价格"},
            {name: "服务时长"},
            {name: "并行工作荷载"},
            {name: "操作"}
        ];
        const _headArr = [];
        const _width = {
            "0" : "5%",
            "1" : "5%",
            "2" : "10%",
            "3" : "10%",
            "4" : "10%",
            "5" : "10%",
            "6" : "10%",
            "7" : "40%"
        };
        //_headArr.push(<th style={{width:'5%'}} role="1" key='' onClick={(e) => this.handleSelect(e)}></th>)
        _headArr.push(data.map((item, index) => <th style={{width: _width[index]}} role="1" key={index}>{item.name}</th>))
        return _headArr;
    }

    tBody(dataList,deleteBtn) {

        return dataList.map(item => <tr key={item.id}>
            <td>{item.id}</td>
            <td>{item.meta.icon ? <img style={{maxWidth: '50px',maxHeight:'50px',verticalAlign:'middle'}} src={ROOTURL + 'asset/images/get.api?hashed=' + item.meta.icon}/> : null}</td>
            <td>{item.name}</td>
            <td>{item.dname}</td>
            <td>{item.cost0}</td>
            <td>{this.changeToMin.bind(this)(item.duration)}</td>
            <td>{item.workload}</td>
            <td>
                <span><NavLink  to={`/PrototypeServiceM/PrototypeServiceEditor/${item.id}`} className="rbtn green">编辑</NavLink></span>
                {deleteBtn ? <span style={{marginLeft: "15px"}}><a  className="rbtn red" onClick={()=>this.handleDelete(item.id)}>删除</a></span> : null }
                <span style={{marginLeft: "15px"}}><NavLink  to={`/PrototypeServiceM/PrototypeServiceEditor${'Preview'}/${item.id}`} className="rbtn green">预览</NavLink></span>
            </td>
        </tr>)
    }

    render() {console.log("服务原型" + "渲染" + this.state.page);
        console.log(this.state)
        return (
            <div className="right-wapper ">
                <div className="rt-wrap">
                    <h2 className="catagory">
                        <Link to={`/PrototypeServiceM`}><span className={style['cata-title-current']}>服务原型</span></Link>
                        <Link to={`/ShopServiceM`}><span className={style['cata-title']}>门店服务类型</span></Link>
                        <Link to={`/BarberServiceM`}><span className={style['cata-title']}>理发师服务类型</span></Link>
                        <Link to={`/PrototypeServiceM/PrototypeServiceEditor`}>
                            <button className="add-btn" />
                        </Link>
                    </h2>
                    <div style={{margin:'20px 0 10px'}}>
                        <label>当前提供的服务项目</label>
                    </div>
                    <Table tHead={this.tHead.bind(this)()} tBody={this.tBody.bind(this)(this.state.dataList,true)} />
                    {this.state.ddServiceList.length ? (<div>
                        <div style={{margin:'30px 0 10px'}}>
                            <label>停止运营的服务项目</label>
                        </div>
                        <Table tHead={this.tHead.bind(this)()} tBody={this.tBody.bind(this)(this.state.ddServiceList,false)} /></div> ): null}
                </div>
                { this.state.delete ?
                    <div id={style.msgDialog}>
                        <div className={style['msgDialog_div']}><h3 id={style['msgDialog_title']}>删除提示？</h3><p id={style['msgDialog_content']}>确认删除？</p>
                            <div className={style['msgDialog_button']}>
                                <button id={style['msgDialog_yes']} onClick={this.handleStoreDelete.bind(this)}>确定</button>
                                <button id={style['msgDialog_no']} onClick={()=>this.setState({delete: !this.state.delete})}>取消</button>
                            </div>
                        </div>
                    </div> : null}
            </div>
        )
    }
}

export default PrototypeServiceM
